package com.example.demo.controller;

import com.example.demo.entity.Longin;
import com.example.demo.service.LonginService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.example.demo.until.MD5Util.md5;

@RestController
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping("/logIn")
public class LogInController {
    @Autowired
    private LonginService longinService;

//    public boolean  userLogin( String name, String password, HttpServletRequest request) {
//        String userPassword=longinService.getLoninPassword(name).getPassword();
//        String pass = md5(password);
//        System.out.println(userPassword);
//        if(userPassword.equals(pass)){
//            HttpSession session = request.getSession(true);
//            session.setAttribute("user", name);
//            return true;
//        }
//        return false;
//    }
    @PostMapping("/userLogin")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> userCredentials) {
        String name = userCredentials.get("name");
        String password = userCredentials.get("password");
        String pass = md5(password);
        Longin longin = longinService.getLoninPassword(name);
        String userPassword = longin.getPassword();
        
        if (userPassword.equals(pass)) {
            // 登录成功，生成Token
            String token = com.example.demo.until.JwtUtil.generateToken(longin.getName());
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("message", "登录成功");
            return new ResponseEntity<>(response, HttpStatus.OK);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "用户名或密码错误");
            return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
        }
    }
}
